package cn.com.dhcc.ddi.stat.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.pubmodule.sysmgr.usermgr.service.CmUserMgrService;
import cn.com.dhcc.app.core.pubmodule.sysmgr.usermgr.vo.UserInfoVo;
import cn.com.dhcc.app.core.util.StrUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Arrays;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.pub.core.util.dateformatter.DateFormatter;
import cn.com.dhcc.app.pub.core.util.echarts.BarChartVo;
import cn.com.dhcc.app.pub.core.util.echarts.LabelStyle;
import cn.com.dhcc.app.pub.core.util.echarts.SeriesLabel;
import cn.com.dhcc.app.pub.core.util.echarts.SeriesVo;
import cn.com.dhcc.app.pub.core.util.echarts.TextStyle;
import cn.com.dhcc.app.pub.core.util.fusioncharts.Categories;
import cn.com.dhcc.app.pub.core.util.fusioncharts.Category;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartDataset;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartSet;
import cn.com.dhcc.app.pub.core.util.fusioncharts.ChartXmlUtil;
import cn.com.dhcc.ddi.node.vo.DataCategory;
import cn.com.dhcc.ddi.stat.service.DataSyncRecStatService;
import cn.com.dhcc.ddi.stat.service.DataSyncSendStatService;
import cn.com.dhcc.ddi.stat.service.DataSyncStatService;
import cn.com.dhcc.ddi.stat.service.NodeStatService;
import cn.com.dhcc.ddi.stat.service.TaskSyncStatService;
import cn.com.dhcc.ddi.stat.vo.DataSyncStatVo;

import javax.servlet.http.HttpSession;

/**
 * 
    * @ClassName: DataSyncStatisticsController
    * @author 18315
    * @date 2016-12-26
    *
 */
@Controller
@RequestMapping("/stat")
public class DataSyncStatisticsController extends BaseController {
	
	Logger logger = Log.getLogger(LOGTYPE.ADAPTER);
	
	@Autowired
	private NodeStatService nodeInfoService;
	@Autowired
	private DataSyncSendStatService sendService;
	@Autowired
	private DataSyncRecStatService recService;
	@Autowired
	private TaskSyncStatService taskSyncStatService;
	@Autowired
	private DataSyncStatService dataSyncStatService;
	@Autowired
	CmUserMgrService userMgrService;
	/**
	 * 列表
	    * @Title: list
	    * @Description: TODO(这里用一句话描述这个方法的作用)
	    * @param @param model
	    * @param @param pager
	    * @param @param 
	    * @param @param orderName
	    * @param @param order
	    * @param @return    参数
	    * @return String    返回类型
	    * @throws
	 */
	@RequestMapping(value = "/nodeSyncStat_list")
	public String list(Model model, Pager pager, String cataId, String statDate,HttpSession httpSession) {
		try {
			WhereCondition nodeParameter = new WhereCondition();
			WhereCondition catasParameter = new WhereCondition();
			Boolean isAdmin = BaseController.getCurrentUserInfo(httpSession).isSuperAdmin();
			String userId = BaseController.getCurrentUserInfo(httpSession).getId();
			if(!isAdmin){
				UserInfoVo currentUser = userMgrService.getUserById(userId);
				if(currentUser != null){
					String nodeIdsStr = currentUser.getExt2();
					if(StrUtil.isNotBank(nodeIdsStr)){
						String[] nodeIds = nodeIdsStr.split(",");
						nodeParameter.and().in("t2.id",nodeIds);
						catasParameter.and().in("t2.node_id", nodeIds);
					}else{
						nodeParameter.and().eq("1","2");
						catasParameter.and().eq("1","2");
					}
				}
			}
			nodeParameter.orderBy("t2.name,t1.exch_type,t3.name");
			List<DataCategory> catas = nodeInfoService.getUserDataCategory(catasParameter);
			
			if(cataId != null && cataId.equals("all")) {
				cataId = null;
			}
			
			if(statDate == null) {
				statDate = DateFormatter.getDateBasedOnToday("yyyy-MM-dd", -1);
			}
			PagerData<DataSyncStatVo> data = dataSyncStatService.getDataStatPagerData(pager, statDate, cataId, nodeParameter);
			
			model.addAttribute("catas", catas);
			model.addAttribute(DATA_KEY, data.getDatas());
			setTotoal(model, data.getTotal());
			return "stat/nodeSyncStat_info_list";
		} catch (Exception e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
	}
	
	/**
	 * 转到各节点统计图页面
	 * @param 
	 * @return
	 * @throws 
	 */
	@RequestMapping("/node_syn_stat")
	public String recSentChart(Model model,HttpSession httpSession) {
		try {
			WhereCondition catasParameter = new WhereCondition();
			Boolean isAdmin = BaseController.getCurrentUserInfo(httpSession).isSuperAdmin();
			String userId = BaseController.getCurrentUserInfo(httpSession).getId();
			if(!isAdmin){
				UserInfoVo currentUser = userMgrService.getUserById(userId);
				if(currentUser != null){
					String nodeIdsStr = currentUser.getExt2();
					if(StrUtil.isNotBank(nodeIdsStr)){
						String[] nodeIds = nodeIdsStr.split(",");
						catasParameter.and().in("t2.node_id", nodeIds);
					}else{
						catasParameter.and().eq("1","2");
					}
				}
			}
			List<DataCategory> catas = nodeInfoService.getUserDataCategory(catasParameter);
			model.addAttribute("catas", catas);
			return "stat/node_syn_stat";
		} catch (Exception e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
		
	}
	
	/**
	 * 获取统计图需要的数据
	 * @param ptaskId
	 * @return
	 * @throws ServiceException
	 */
	@ResponseBody
	@RequestMapping(value="/get_nodeStat", method = RequestMethod.POST)
	public Map<String,Object> generateRecSentData(int dateScope, int dataScope, String date, String cataId,HttpSession httpSession) {
		try {	
			//List<DataCategory> catas = nodeInfoService.getDataCategory();
			
			//发送数据
			//List<TaskSyncStatVo> sendData = taskSyncStatService.getNodeStatData("0", date, cataId, dateScope);
			//接收数据
			//List<TaskSyncStatVo> recvData = taskSyncStatService.getNodeStatData("1", date, cataId, dateScope);
			WhereCondition nodeParameter = new WhereCondition();
			String dataParameter = "";
			WhereCondition cateParameter =  new WhereCondition();
			Boolean isAdmin = BaseController.getCurrentUserInfo(httpSession).isSuperAdmin();
			String userId = BaseController.getCurrentUserInfo(httpSession).getId();
			if(!isAdmin){
				UserInfoVo currentUser = userMgrService.getUserById(userId);
				if(currentUser != null){
					String nodeIdsStr = currentUser.getExt2();
					if(StrUtil.isNotBank(nodeIdsStr)){
						String[] nodeIds = nodeIdsStr.split(",");
						nodeParameter.and().in("t1.id",nodeIds);
						for(int i = 0; i < nodeIds.length; i++){
							if(i == 0){
								dataParameter += "'"+nodeIds[i]+"'";
							}else{
								dataParameter += ",'"+nodeIds[i]+"'";
							}
						}
						dataParameter = " and stat.node_id in ("+ dataParameter +")";
						cateParameter.and().in("t1.node_id",nodeIds);
					}else{
						nodeParameter.and().eq("1","2");
						dataParameter = " and 1 = 2 ";
						cateParameter.and().eq("1","2");
					}
				}
			}

			nodeParameter.orderBy("t1.orgcode desc");//查出来的名称排序要和查出来的数据排序一致
			//set categories
			List<String> categories = dataSyncStatService.getDistinctNodes(nodeParameter,dateScope, date);
			
			//get caption
			String cateName = "";
			if(dataScope == 0) {
				cateName = "频次";
			} else {
				cateName = "数据量";
			}
			
			String caption = date + " ETL数据同步" + cateName;
			
			//legend
			List<String> cataNames = dataSyncStatService.getDistinctCates(cateParameter,dateScope, date);
			
			
			//data
			List<SeriesVo> series = new ArrayList<SeriesVo>();
			
			if(cataId != null && cataId.equals("all")) {
				cataId = null;
			}
			//发送
			List<DataSyncStatVo> sendList = dataSyncStatService.getDataStatSend(dateScope, date, cataId,dataParameter);
			for(int i = 0; i < sendList.size(); i++) {
				DataSyncStatVo sendVo = sendList.get(i);
				SeriesVo mySeries = new SeriesVo();
				if(sendVo.getDatacatagoryName() == null){
					continue;
				}
				mySeries.setName(sendVo.getDatacatagoryName());
				mySeries.setType("bar");
				mySeries.setStack("发送");
				
				List<String> valueList = new ArrayList<String>();
				if(dataScope == 0) {
					String[] totalList = sendVo.getTotalList().split(",");
					valueList = Arrays.asList(totalList);
				} else {
					String[] dataSizeList = sendVo.getDataSizeList().split(",");
					valueList = Arrays.asList(dataSizeList);
				}
				
				mySeries.setData(valueList);
				mySeries.setBarMaxWidth("40");
				//最后一个加label
				if(i == sendList.size() - 1) {
					LabelStyle myLabelStyle = new LabelStyle();
					myLabelStyle.setTextStyle(new TextStyle("#428BCA"));
					myLabelStyle.setFormatter("发送");
					myLabelStyle.setPosition("right");
					myLabelStyle.setShow(true);
					SeriesLabel myLabel = new SeriesLabel();
					myLabel.setNormal(myLabelStyle);
					mySeries.setLabel(myLabel);
				}
				series.add(mySeries);
			}
			
			
			List<DataSyncStatVo> recvList = dataSyncStatService.getDataStatRecv(dateScope, date, cataId,dataParameter);//接收
			for(int i = 0; i < recvList.size(); i++) {
				DataSyncStatVo recvVo = recvList.get(i);
				SeriesVo mySeries = new SeriesVo();
				if(recvVo.getDatacatagoryName() == null){
					continue;
				}
				mySeries.setName(recvVo.getDatacatagoryName());
				mySeries.setType("bar");
				mySeries.setStack("接收");
				
				List<String> valueList = new ArrayList<String>();
				if(dataScope == 0) {
					String[] totalList = recvVo.getTotalList().split(",");
					valueList = Arrays.asList(totalList);
				} else {
					String[] dataSizeList = recvVo.getDataSizeList().split(",");
					valueList = Arrays.asList(dataSizeList);
				}
				
				mySeries.setData(valueList);
				mySeries.setBarMaxWidth("40");
				//最后一个加label
				if(i == sendList.size() - 1) {
					LabelStyle myLabelStyle = new LabelStyle();
					myLabelStyle.setTextStyle(new TextStyle("#428BCA"));
					myLabelStyle.setFormatter("接收");
					myLabelStyle.setPosition("right");
					myLabelStyle.setShow(true);
					SeriesLabel myLabel = new SeriesLabel();
					myLabel.setNormal(myLabelStyle);
					mySeries.setLabel(myLabel);
				}
				series.add(mySeries);
			}

			BarChartVo chartData = new BarChartVo(caption, series, categories);
			chartData.setLegendData(cataNames);
				
			return jsonSuccessDataResult("获取统计图", chartData);
		} catch(ServiceException e) {
			logger.error(e);
			return jsonFailResult("获取统计图失败");
		}
	}

	
 
	/**
	 * 转到各节点频次统计图页面
	 * @param 
	 * @return
	 * @throws 
	 */
	@RequestMapping("/node_syn_total")
	public String recSentChart1(Model model) {
	try {
		model.addAttribute("List", nodeInfoService.getDataCategory());
		return "stat/node_syn_total";
	} catch (Exception e) {
		logger.error("操作失败", e);
		return toAlertPage(model, e.getMessage());
	}
	}
	
	/**
	 * 获取统计图需要的数据
	 * @param ptaskId
	 * @return
	 * @throws ServiceException
	 */
	@ResponseBody
	@RequestMapping(value="/get_nodeStatTotal", method = RequestMethod.POST)
	public Map<String,Object> generateRecSentTotal(String scope, String date) {
		//返回的xml
		Map<String,Object> output = new HashMap<String, Object>();		
		
		//set categories
		Categories cate = new Categories();
		try {
			List<Category> cList = new ArrayList<Category>();
			List<String> names = nodeInfoService.getNodeNames();
			for(String name:names) {
				cList.add(new Category(name));
			}
			cate.setCategory(cList);
		} catch (ServiceException e) {
			logger.error(e);
		}

		//set datasets i.e. receive and sent
		ChartDataset sentDataSet = new ChartDataset("发送");
		ChartDataset receiveDataSet = new ChartDataset("接收");
		sentDataSet.setColor("F6BD0F");
		receiveDataSet.setColor("AFD8F8");
		
		//按顺序获取节点id
		List<String> ids = new ArrayList<String>();
		try {
			ids = nodeInfoService.getNodeId();
		} catch (ServiceException e) {
			logger.error(e);
		}
		
		int s = 0;
		try {
			s = Integer.parseInt(scope);
		} catch (NumberFormatException e) {
			logger.error(e);
		}
		
		//send
		List<ChartSet> sendList = new ArrayList<ChartSet>();
		try {
			
			Map<String, String> sendMap = sendService.getSendTotalCount(s, date);
			
			for(String id: ids) {
				sendList.add(new ChartSet(sendMap.get(id)));
			}
		} catch (ServiceException e) {
			logger.error(e);
		}
		sentDataSet.setSet(sendList);
		
		//receive
		List<ChartSet> receiveList = new ArrayList<ChartSet>();
		try {
			Map<String, String> receiveMap = recService.getRecTotalCount(s, date);
			
			//按顺序添加值
			for(String id: ids) {
				receiveList.add(new ChartSet(receiveMap.get(id)));
			}
		} catch (ServiceException e) {
			logger.error(e);
		}
		receiveDataSet.setSet(receiveList);
		
		
		//add values to chart
		List<ChartDataset> dataSetList = new ArrayList<ChartDataset>();
		dataSetList.add(sentDataSet);
		dataSetList.add(receiveDataSet);
		
		//generate xml file	
		output.put("chart", ChartXmlUtil.getXmlForColumn("数据同步执行频率", cate, dataSetList,""));
		
		return output;	
	}

}
